package com.nts.visionworks.core.image.scaling;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import java.io.IOException;


import javax.activity.InvalidActivityException;
import javax.imageio.ImageIO;

import org.apache.commons.fileupload.InvalidFileNameException;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mortennobel.imagescaling.ResampleOp;
import com.nts.visionworks.core.image.ImageType;

public class ImageScaler
{
	private static final Logger logger = LoggerFactory.getLogger(ImageScaler.class);
	
	public static boolean scaleImage(String sourcePath, String scalingPath
			, int scalingMaxWidth, int scalingMaxHeight) throws InvalidActivityException, FileNotFoundException, IOException
	{
		boolean result = false;
		
		File sourceFile = new File(sourcePath);
		
		if (!sourceFile.exists())
		{
			throw new FileNotFoundException("원본 파일이 존재하지 않습니다.");
		}
		
		String extension = FilenameUtils.getExtension(sourcePath);
		
		ImageType imageType = ImageType.getType(extension);
		
		if (imageType.equals(ImageType.UNKNOWN))
		{
			throw new InvalidFileNameException(sourcePath, "주어진 파일의 확장자를 지원하지 않습니다.");
		}
		
		FileOutputStream outputStream = null;
		
		try
		{
			BufferedImage sourceImage = ImageIO.read(sourceFile);
			
			int sourceWidth = sourceImage.getWidth();
			int sourceHeight = sourceImage.getHeight();
			
			double sourceRatio = (double)sourceWidth / (double)sourceHeight;
			
			if (sourceWidth > sourceHeight)
			{
				scalingMaxHeight = (int)(scalingMaxWidth / sourceRatio);
			}
			else
			{
				scalingMaxWidth = (int)(scalingMaxHeight / sourceRatio);
			}
			
			ResampleOp  resampleOp = new ResampleOp(100, 200);
			
			BufferedImage scaledImage = resampleOp.filter(sourceImage, null);
			
			outputStream = new FileOutputStream(scalingPath);
			
			ImageIO.write(scaledImage, extension, outputStream);
			
			result = true;
		}
		catch (FileNotFoundException error)
		{
			logger.error("섬네일 파일이 없습니다. 섬네일 파일을 만들지 못했습니다.", error);
		}
		catch (SecurityException error)
		{
			logger.error("섬네일 경로에 접근이 불가능합니다.", error);
		}
		catch (IOException error)
		{
			logger.error("섬네일 인코드 과정에서 I/O 오류가 발생했습니다.", error);
		}
		finally
		{
			if (outputStream != null)
			{
				outputStream.close();
			}
		}
		
		return result;
	}
}